package cn.dzhang.spring.boot.remoting;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Component;

@Component
public class BasicAuthenticationFilter implements Filter {
	private static final Log log = LogFactory
			.getLog(BasicAuthenticationFilter.class);

	public BasicAuthenticationFilter() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		final boolean debug = log.isDebugEnabled();
		final HttpServletRequest request = (HttpServletRequest) req;
		final HttpServletResponse response = (HttpServletResponse) res;

		String header = request.getHeader("Authorization");

		if (header == null || !header.startsWith("Basic ")) {
			chain.doFilter(request, response);
			return;
		}

		try {
			String[] tokens = extractAndDecodeHeader(header, request);
			assert tokens.length == 2;

			String username = tokens[0];
			String password = tokens[1];

			if (debug) {
				log.debug("Basic Authentication Authorization header found for user '"
						+ username + "'");
			}

			AuthenticationContextHolder
					.setCurrentAuthentication(new Authentication(username,
							password));

		} catch (Exception failed) {
			failed.printStackTrace();
			return;
		}

		chain.doFilter(request, response);
	}

	private String[] extractAndDecodeHeader(String header,
			HttpServletRequest request) throws IOException {

		byte[] base64Token = header.substring(6).getBytes("UTF-8");
		byte[] decoded;
		try {
			decoded = Base64.decodeBase64(base64Token);
		} catch (IllegalArgumentException e) {
			throw new IllegalArgumentException(
					"Failed to decode basic authentication token");
		}

		String token = new String(decoded, getCredentialsCharset(request));

		int delim = token.indexOf(":");

		if (delim == -1) {
			throw new IllegalArgumentException(
					"Invalid basic authentication token");
		}
		return new String[] { token.substring(0, delim),
				token.substring(delim + 1) };
	}

	protected String getCredentialsCharset(HttpServletRequest httpRequest) {
		return "UTF-8";
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.err.println("BasicAuthenticationFilter.init()");
	}

	@Override
	public void destroy() {
		System.err.println("BasicAuthenticationFilter.destroy()");
	}

}
